#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <fcntl.h>

#define BUFF_SIZE 1024

int main(int argc, char *argv[]) {
    // check parameters
    if (argc != 3) {
        printf("input parameter error! Format should be : %s <source_file> <destination_file.\n", argv[0]);
        return -1;
    }

    // open source file
    int source_fd = open(argv[1], O_RDONLY);
    if (source_fd == -1) {
        printf("open %s failed!\n", argv[1]);
        return -1;
    }

    // open destination file
    int des_fd = open(argv[2], O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
    if (des_fd == -1) {
        printf("open %s failed!\n", argv[2]);
        return -1;
    }

    char buf[BUFF_SIZE];
    while (1) {
        int read_result = read(source_fd, buf, BUFF_SIZE);
        if (read_result == -1) {
            printf("read %s failed!\n", argv[1]);
            return -1;
        }
        else if (read_result == 0) {
            printf("copy success(^_^)\n");
            return 0;
        }
        else if (read_result > 0) {
            // read_result indicates the number of bytes read
            int write_result = write(des_fd, buf, read_result);
            if (write_result != read_result) {
                printf("write %s failed!\n", argv[2]);
                return -1;
            }
        }
    }

    return 0;
}
